// 云函数入口文件和一些初始化操作
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: "meeting2021-2glaokedaf06ae2e",
})
const ydb = cloud.database()
// 云函数入口函数
exports.main = async (event) => {

  //openid name img meeetingInfoId appointmentTime checkFlag checkMyDate checkDay needReason meetingPoint needDes isDone isDoneReason
  //首先查询是不是有人在此人申请的过程中已经预约了
  var isUasble = "false";
  const res = await ydb.runTransaction(
    async transaction => {
      /*首先判断当日预约的状态*/
      //获取当日预约的状态
      const roomRes = await transaction.collection('meetingRoom').doc(event.meeetingInfoId).get()
      console.log("roomRes")
      console.log(roomRes)
      var queueNum = roomRes.data.timeList.length - (3 - parseInt(event.checkFlag))
      console.log("queueNum "+queueNum)
      console.log("roomRes.data.timeList[queueNum]")
      console.log(roomRes.data.timeList[queueNum])
      // console.log(roomRes.data.timeList[queueNum].openTime)
      let nowState = roomRes.data.timeList[queueNum].openTime[event.checkDay].state
      console.log("nowState "+nowState)
      let appointmentId = String(Date.now())
      if (nowState == 1) {
        isUasble = "true"
        //没人预约则修改会议室预约状态，
        const lostRes = await transaction.collection('meetingRoom').doc(event.meeetingInfoId).update({
          data: {

            [`timeList.${queueNum}.openTime.${event.checkDay}.state`]: 2,
            [`timeList.${queueNum}.openTime.${event.checkDay}.appointmentId`]: appointmentId,
          }
        })
        //添加申请表
        let addNew = await transaction.collection('appointment').add({
          data: {
            _id: appointmentId,
            _openid: event.openid,
            meetingInfoId: event.meeetingInfoId,
            meetingName:event.meeetingName,
            meetingPublishAdm:event.meetingPublishAdm,
            appointmentTime: event.appointmentTime,
            nickName: event.name,
            userImg: event.img,
            checkMyDate: event.checkMyDate,
            checkDay: event.checkDay,
            timeListIndex:queueNum,
            needReason: event.needReason,
            meetingPoint: event.meetingPoint,
            needDes: event.needDes,
            isDone: event.isDone,
            isDoneReason: event.isDoneReason,
            roomStatus:2
          },
        })
      } 
    })
    return isUasble
}